import { css } from "@emotion/css";
import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Grid,
  Input,
  Message,
  Select,
  Space,
} from "@arco-design/web-react";
import { useBuildingEdit } from "../../hooks/useBuildingEdit.ts";
import { useMutation, useQuery } from "react-query";
import { useAPI } from "../../hooks/useAPI.ts";
import {
  BuildingRoomCameraInfo,
  Floor,
  Room,
} from "../../api/types/room-camera.tsx";
import { Role, SearchUserParams } from "../../api/types/system-user.ts";
import { Link } from "../../components/Link";
import { useParams } from "../../hooks/useParams.ts";
import { IconLoading, IconRight } from "@arco-design/web-react/icon";
import { useLocation, useNavigate } from "react-router-dom";
import GridItem from "@arco-design/web-react/es/Grid/grid-item";

const buildingParams: SearchUserParams = {
  roleIds: Role.BuildingAdmin,
  pageNum: 1,
  pageSize: 1000,
};

export default function EditBuilding() {
  const api = useAPI();
  const buildingEditor = useBuildingEdit();
  let { id } = useParams();
  const navigate = useNavigate();
  const location = useLocation();
  const isReadonly = !!new URLSearchParams(location.search).get("isReadonly");
  const { error, isLoading } = useQuery(
    ["query-building-info", id],
    async () => {
      const response = await api.getBuildingInfoById(id!);
      if (!response.data.data) {
        throw new Error("No Data");
      }
      return response.data.data;
    },
    {
      enabled: id !== undefined,
      refetchOnWindowFocus: false,
      refetchOnReconnect: false,
      onSuccess(buildingData) {
        buildingEditor.setBuilding({
          name: buildingData.name,
          adminId: buildingData.managers?.[0].userId,
          telephone: buildingData.phone,
          floors:
            buildingData.floors?.map((floor) => ({
              id: floor.id,
              name: floor.name,
              rooms:
                floor.rooms?.map((room) => ({
                  id: room.id,
                  name: room.name,
                })) ?? [],
            })) ?? [],
        });
      },
      retry: 2,
    },
  );

  const { data: buildingAdminList } = useQuery(
    [
      "query-building-admin-list",
      buildingParams.roleIds,
      buildingParams.pageNum,
      buildingParams.pageSize,
    ],
    async () => {
      const response = await api.getSystemUserList(buildingParams);
      return response.data.data;
    },
  );

  const submitForm = useMutation(async () => {
    try {
      const formData = buildingEditor.building;
      const convertedFloors: Floor[] = formData.floors.map((floorData) => {
        const convertedRooms: Room[] = floorData.rooms.map((roomData) => {
          const room: Room = {
            name: roomData.name,
            del: roomData.del,
            id: roomData.id,
          };
          return room;
        });
        const floor: Floor = {
          name: `${floorData.name.replace(/\D/g, "")}层`,
          rooms: convertedRooms,
          id: floorData.id,
          del: floorData.del,
        };
        return floor;
      });

      const buildingInfo: BuildingRoomCameraInfo = {
        id: id ? parseInt(id!, 10) : undefined,
        floors: convertedFloors,
        name: `${formData.name.replace(/\D/g, "")}号楼`,
        phone: formData.telephone,
        managers: [
          {
            userId: formData.adminId,
          },
        ],
      };
      if (!buildingInfo.name || !buildingInfo.managers?.[0].userId) {
        Message.error("请填写必要信息");
        return;
      }
      await api.saveBuilding(buildingInfo);
      Message.success("操作成功");
      if (!id) {
        navigate("/buildingManagement/index", { replace: true });
      }
      // await refetch();
    } catch (error) {
      if (error instanceof Error) {
        Message.error(error.message);
      } else {
        Message.error("操作失败，请稍后重试");
      }
    }
  });

  const breadcrumb = (
    <Breadcrumb
      className={css`
        padding: 12px;
        border-radius: 1px;
        font-weight: bold;
        border-left: 5px solid rgb(var(--primary-6));
        margin-bottom: 20px;
      `}
      separator={<IconRight />}
    >
      <Breadcrumb.Item style={{ fontWeight: 400 }}>
        <Link
          to="/buildingManagement/index"
          style={{
            textDecoration: "none",
            transition: "color 0.3s",
            fontWeight: "bold",
            fontSize: "15px",
          }}
        >
          楼栋管理
        </Link>
      </Breadcrumb.Item>
      <Breadcrumb.Item>
        {isReadonly ? "查看楼栋" : id ? "编辑楼栋" : "添加楼栋"}
      </Breadcrumb.Item>
    </Breadcrumb>
  );

  if (isLoading) {
    return (
      <div
        className={css`
          width: 100%;
          display: flex;
          flex-direction: column;
        `}
      >
        {breadcrumb}
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            color: "rgb(var(--primary-6))",
            paddingBottom: "20px",
          }}
        >
          <IconLoading />
        </div>
      </div>
    );
  }

  if (error) {
    if (error instanceof Error) {
      return (
        <div
          className={css`
            width: 100%;
            display: flex;
            flex-direction: column;
          `}
        >
          {breadcrumb}
          <div>
            Error: <br />
            {error.message}
          </div>
        </div>
      );
    }
    return <div>Error</div>;
  }

  return (
    <div>
      <div
        className={css`
          width: 100%;
          display: flex;
          flex-direction: column;
        `}
      >
        {breadcrumb}
        <Card
          bordered={false}
          className={css`
            box-shadow: 0 2px 3px 0 #a5a3ae4d;
            display: flex;
            flex-direction: column;
            margin-bottom: 20px;
          `}
        >
          {!isReadonly && (
            <div
              className={css`
                display: flex;
                justify-content: space-between;
              `}
            >
              <div>
                <Button
                  htmlType="submit"
                  type="primary"
                  style={{ marginLeft: "10px" }}
                  loading={submitForm.isLoading}
                  onClick={() => {
                    submitForm.mutateAsync();
                  }}
                >
                  保存当前
                </Button>
              </div>
            </div>
          )}
        </Card>
        <Card
          bordered={false}
          className={css`
            box-shadow: 0 2px 3px 0 #a5a3ae4d;
            display: flex;
            flex-direction: column;
            margin-bottom: 20px;
          `}
        >
          <div
            className={css`
              font-size: 15px;
              font-weight: 400;
              line-height: 24px;
            `}
          >
            楼栋信息
          </div>

          <Form layout="inline" style={{ marginTop: "20px" }}>
            <Form.Item
              label="楼栋号"
              disabled={isReadonly}
              rules={[
                {
                  required: true,
                  validator(value, cb) {
                    if (!/^\d+$/.test(value)) {
                      return cb("只能输入数字");
                    }
                    cb();
                  },
                },
              ]}
            >
              <Input
                style={{ width: "200px" }}
                placeholder="请输入楼栋号"
                value={buildingEditor.building.name?.replace(/\D/g, "")}
                onChange={(value) => {
                  buildingEditor.inputBuildingName(value?.toString() ?? "");
                }}
              />
            </Form.Item>
            <Form.Item
              label="楼管"
              disabled={isReadonly}
              rules={[
                {
                  required: true,
                  message: "楼管不得为空",
                },
              ]}
            >
              <Select
                disabled={isReadonly}
                style={{ width: "200px" }}
                placeholder="请选择管家"
                options={buildingAdminList?.rows.map((item) => ({
                  label: item.nickName,
                  value: item.userId,
                }))}
                filterOption={(input, option) =>
                  option?.props.children
                    .toLowerCase()
                    .includes(input.toLowerCase())
                }
                showSearch
                value={buildingEditor.building.adminId}
                onChange={(value) =>
                  buildingEditor.chooseBuildingAdminId(value)
                }
              />
            </Form.Item>
            <Form.Item
              disabled={isReadonly}
              label="楼管电话"
              rules={[
                {
                  required: true,
                  message: "楼栋电话不得为空",
                },
                {
                  validator(value, cb) {
                    const phoneNumberRegex = /^1[3-9]\d{9}$/;
                    if (value && !phoneNumberRegex.test(value)) {
                      return cb("请输入正确格式的电话号码");
                    }
                    return cb();
                  },
                },
              ]}
            >
              <Input
                disabled={isReadonly}
                style={{ width: "200px" }}
                placeholder="请输入楼栋电话"
                value={buildingEditor.building.telephone}
                onChange={(value) =>
                  buildingEditor.inputBuildingTelephone(value)
                }
              />
            </Form.Item>

            <Button
              htmlType="button"
              type="primary"
              onClick={() => buildingEditor.addFloor()}
            >
              添加楼层
            </Button>
          </Form>

          <div
            style={{ display: "flex", flexDirection: "column", gap: "12px" }}
          >
            {buildingEditor.building.floors
              .filter((floor) => !floor.del)
              .map((floor, floorIndex) => (
                <div
                  key={`floor-${floorIndex}`}
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    borderLeft: "1px dashed #DBDADE ",
                    paddingLeft: "10px",
                    marginTop: "20px",
                  }}
                >
                  <div
                    style={{
                      display: "flex",
                      flexDirection: "row",
                      alignItems: "center",
                      position: "relative",
                    }}
                  >
                    <div
                      style={{
                        width: "6px",
                        height: "6px",
                        backgroundColor: "#FF9900",
                        borderRadius: "50%",
                        marginRight: "6px",
                        position: "absolute",
                        left: "-13.5px",
                        zIndex: 10,
                      }}
                    ></div>
                    <span>楼层</span>
                    <Input
                      disabled={isReadonly}
                      style={{
                        width: "180px",
                        margin: "10px",
                      }}
                      value={floor.name.replace(/\D/g, "")}
                      onChange={(value) =>
                        buildingEditor.inputFloorName(floorIndex, value)
                      }
                    />
                    {!isReadonly && (
                      <Space>
                        <Button
                          htmlType="button"
                          type="outline"
                          onClick={() => buildingEditor.addRoom(floorIndex)}
                        >
                          添加房间
                        </Button>
                        <Button
                          htmlType="button"
                          type="outline"
                          status="danger"
                          onClick={() => {
                            if (floor.id == null) {
                              buildingEditor.removeFloor(floorIndex);
                            } else {
                              buildingEditor.setDelFloor(floorIndex);
                            }
                          }}
                        >
                          删除楼层
                        </Button>
                      </Space>
                    )}
                  </div>
                  <Grid
                    cols={{ xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 8 }}
                    colGap={6}
                    rowGap={8}
                    className="grid-responsive-demo"
                  >
                    {floor.rooms
                      .filter((room) => !room.del)
                      .map((room, roomIndex) => (
                        <GridItem
                          key={`room-${floorIndex}-${roomIndex}`}
                          className="demo-item"
                        >
                          <Input
                            disabled={isReadonly}
                            style={{ width: room.id ? "80px" : "120px" }}
                            value={room.name}
                            onChange={(value) =>
                              buildingEditor.renameRoom(
                                floorIndex,
                                roomIndex,
                                value,
                              )
                            }
                          />
                          {!room.id && (
                            <Button
                              htmlType="button"
                              type="outline"
                              status="success"
                              onClick={() => {
                                submitForm.mutateAsync();
                              }}
                            >
                              保存
                            </Button>
                          )}
                          {!isReadonly && (
                            <Button
                              htmlType="button"
                              type="outline"
                              status="danger"
                              onClick={() => {
                                if (room.id == null) {
                                  buildingEditor.removeRoom(
                                    floorIndex,
                                    roomIndex,
                                  );
                                } else {
                                  buildingEditor.setDelRoom(
                                    floorIndex,
                                    roomIndex,
                                  );
                                }
                              }}
                            >
                              删除
                            </Button>
                          )}
                        </GridItem>
                      ))}
                  </Grid>
                </div>
              ))}
          </div>
        </Card>
      </div>
    </div>
  );
}
